package com.chen.websocket;

import cn.hutool.json.JSONUtil;
import com.chen.judge.codesandbox.model.JudgeResult;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/judge/{problemSubmitId}")
public class WebSocketServer {
    //存放会话对象
//    private static Map<Integer, Session> sessionMap = new HashMap();
    private static final Map<Integer, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     *
     * @param session
     * @param problemSubmitId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("problemSubmitId") Integer problemSubmitId) {
        System.out.println("WebSocket客户端：" + problemSubmitId + "建立连接");
        sessionMap.put(problemSubmitId, session);
    }


    /**
     * 连接关闭调用的方法
     *
     * @param problemSubmitId
     */
    @OnClose
    public void onClose(@PathParam("problemSubmitId") Integer problemSubmitId) {
        System.out.println("WebSocket客户端" + problemSubmitId + "连接断开");
        sessionMap.remove(problemSubmitId);
    }

    /**
     * 使用代码提交id发给指定的客户端
     *
     * @param problemSubmitId
     * @param judgeResult
     */
    public void sendClient(Integer problemSubmitId, JudgeResult judgeResult) {
        Session session = sessionMap.get(problemSubmitId);
        try {
            //服务器向客户端发送消息
            String jsonStr = JSONUtil.toJsonStr(judgeResult);
            session.getBasicRemote().sendText(String.valueOf(jsonStr));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
